import mido
import random


mid = mido.MidiFile()
track = mido.MidiTrack()
mid.tracks.append(track)

track.append(mido.MetaMessage('set_tempo', tempo=500000, time=0))
track.append(mido.MetaMessage('track_name', name='Piano 1', time=0))
track.append(mido.Message('program_change', program=1, time=0))  # 这个音轨使用的乐器

melodyTime = 4800 #music length for now it is 10 tempo
wholeTime = 0 #for computing
while wholeTime < melodyTime:
    noteTempo = random.randint(1,2) * 240  #120 is a quarter beat
    pitchNote = random.randint(1,12) + 55 #three octs
    # print("pace:"+str(noteTempo))
    # print("start:"+str(wholeTime))
    track.append(mido.Message('note_on', note=pitchNote, velocity=127,time = 0))
    wholeTime = wholeTime + noteTempo
    print("pitch:"+str(pitchNote)+"\n")
    track.append(mido.Message('note_off', note=pitchNote, velocity=127,time = noteTempo))
# track.append(mido.Message('note_on', note=60, velocity=127,time = 0))
# track.append(mido.Message('note_off', note=60, velocity=127,time = 360))
# track.append(mido.Message('note_on', note=61, velocity=127,time = 0))
# track.append(mido.Message('note_off', note=61, velocity=127,time = 480))
    
mid.save('test.mid')